package com.m1905hd.user.shiro.realm;

import com.m1905hd.user.entity.User;
import com.m1905hd.user.resource.Global;
import com.m1905hd.user.service.UserService;
import com.m1905hd.user.shiro.captcha.exception.CaptchaException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author weiwei.huang
 * @email ihuangweiwei@163.com
 * @date 15/3/30
 */
public class SystemAuthorizingRealm extends AuthorizingRealm {

    UserService userService;

    private static final String ALGORITHM = "SHA-1";

    private static final int INTERATIONS = 1024;


    public SystemAuthorizingRealm() {
        super();
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);
        matcher.setHashIterations(INTERATIONS);
        setCredentialsMatcher(matcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(this.userService.findRoles(username));
        authorizationInfo.setStringPermissions(this.userService.findPermissions(username));
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        com.m1905hd.user.shiro.captcha.UsernamePasswordToken token = (com.m1905hd.user.shiro.captcha.UsernamePasswordToken) authenticationToken;
        /**
         * 是否开启验证码验证
         */
        if (Global.IS_OPEN_CAPTCHA) {
            Session session = SecurityUtils.getSubject().getSession();
            String code = (String) session.getAttribute(Global.VALIDATE_CODE);
            if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().trim().equals(code)) {
                throw new CaptchaException("验证码错误");
            }
        }

        User user = userService.findByUserName(token.getUsername());
        if (user != null) {
            //判断用户账号是否可用
            if (user.getAvailable() == 0) {
                throw new DisabledAccountException();
            }
            return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
        }
        return null;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
}
